<template>
	<view class="reviews-container">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="nav-left" @click="goBack">
				<u-icon name="arrow-left" size="20" color="#333"></u-icon>
			</view>
			<view class="nav-title">商品评价</view>
			<view class="nav-actions">
				<view class="action-icon" @click="showMoreOptions">
					<u-icon name="more-dot-fill" size="20" color="#999"></u-icon>
				</view>
				<view class="action-icon" @click="showFilter">
					<u-icon name="minus" size="20" color="#999"></u-icon>
				</view>
				<view class="action-icon" @click="showSort">
					<u-icon name="setting" size="20" color="#999"></u-icon>
				</view>
			</view>
		</view>

		<!-- 评价统计区域 -->
		<view class="review-summary">
			<view class="summary-left">
				<text class="review-count">评价({{ totalReviews }})</text>
			</view>
			<view class="summary-right">
				<text class="positive-rate">好评率 {{ positiveRate }}%</text>
			</view>
		</view>

		<!-- 筛选标签 -->
		<view class="filter-tabs">
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'all' }"
				@click="switchTab('all')"
			>
				<text class="tab-text">全部({{ allCount }})</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'positive' }"
				@click="switchTab('positive')"
			>
				<text class="tab-text">好评({{ positiveCount }})</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'neutral' }"
				@click="switchTab('neutral')"
			>
				<text class="tab-text">中评({{ neutralCount }})</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'negative' }"
				@click="switchTab('negative')"
			>
				<text class="tab-text">差评({{ negativeCount }})</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'withImage' }"
				@click="switchTab('withImage')"
			>
				<text class="tab-text">有图({{ withImageCount }})</text>
			</view>
		</view>

		<!-- 提示文字 -->
		<view class="instruction-text">
			<text class="instruction">为你挑选真实、有帮助的评价</text>
		</view>

		<!-- 评价列表 -->
		<view class="reviews-list">
				<view 
					class="review-item" 
					:class="{ highlighted: review.highlighted }"
					:id="'review-' + (review.id || index)"
					v-for="(review, index) in filteredReviews" 
					:key="index"
				>
				<view class="review-header">
					<view class="user-info">
						<view class="user-avatar">
							<u-avatar
								:src="review.avatar"
								size="60"
								shape="circle"
								:defaultSrc="defaultAvatar"
							></u-avatar>
						</view>
						<view class="user-details">
							<text class="username">{{ review.username }}</text>
							<view class="rating">
								<u-icon v-for="star in 5" :key="star" name="star-fill" size="16" :color="star <= (review.rating || 0) ? '#ff4757' : '#ddd'"></u-icon>
							</view>
						</view>
					</view>
					<view class="review-date">
						<text class="date-text">{{ review.date }}</text>
					</view>
				</view>
				<view class="review-content">
					<text class="content-text">{{ review.content }}</text>
				</view>
				<view class="review-images" v-if="review.images && review.images.length > 0">
					<view 
						class="image-item" 
						v-for="(image, imgIndex) in review.images" 
						:key="imgIndex"
						@click="previewImage(review.images, imgIndex)"
					>
					<image 
						:src="image" 
						mode="aspectFill"
						style="position:absolute;top:0;left:0;width:100%;height:100%;border-radius:8rpx;"
					></image>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore">
			<u-loadmore 
				:status="loadMoreStatus" 
				@loadmore="loadMore"
			></u-loadmore>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="filteredReviews.length === 0">
			<view class="empty-icon">
				<u-icon name="chat" size="80" color="#ddd"></u-icon>
			</view>
			<text class="empty-text">暂无评价</text>
		</view>
	</view>
</template>

<script>
import { get } from '@/utils/request.js'
export default {
	data() {
		return {
			activeTab: 'all',
			totalReviews: 0,
			positiveRate: 0,
			allCount: 0,
			positiveCount: 0,
			neutralCount: 0,
			negativeCount: 0,
			withImageCount: 0,
			defaultAvatar: '/static/logo.png',
			reviews: [],
			productId: null,
			hasMore: false,
			loadMoreStatus: 'nomore',
			// 缓存用户信息，key为userId
			userInfoMap: {}
		}
	},
	computed: {
		filteredReviews() {
			if (this.activeTab === 'all') {
				return this.reviews;
			} else if (this.activeTab === 'positive') {
				return this.reviews.filter(review => review.rating >= 4);
			} else if (this.activeTab === 'neutral') {
				return this.reviews.filter(review => review.rating === 3);
			} else if (this.activeTab === 'negative') {
				return this.reviews.filter(review => review.rating <= 2);
			} else if (this.activeTab === 'withImage') {
				return this.reviews.filter(review => review.images && review.images.length > 0);
			}
			return this.reviews;
		}
	},
	onLoad(options) {
		// 页面加载时获取商品ID和默认标签
		if (options.productId) {
			this.productId = options.productId;
		}
		if (options.tab) {
			const safe = ['all','positive','neutral','negative','withImage']
			this.activeTab = safe.includes(options.tab) ? options.tab : 'all'
		}
		// 记录需要定位的评论
		this.targetReviewId = options.reviewId || null
		this.targetReviewKey = options.reviewKey || ''
		this.loadReviews();
	},
	methods: {
		// 请求评价列表
		async fetchAppraiseList(params) {
			return get('/appraise/list', params)
		},
		// 请求单个用户信息
		async fetchUserInfo(userId) {
			if (!userId) return null
			return get(`/user/${userId}`)
		},
		// 批量加载用户信息并写入 userInfoMap
		async loadUserInfos(userIds = []) {
			const ids = Array.from(new Set((userIds || []).filter(Boolean)))
			if (ids.length === 0) return
			const results = await Promise.allSettled(ids.map(id => this.fetchUserInfo(id)))
			results.forEach((res, idx) => {
				const id = ids[idx]
				if (res.status === 'fulfilled') {
					const payload = res.value
					const data = (payload && payload.data) || payload || {}
					this.$set(this.userInfoMap, id, {
						nickname: data.userNickname || '',
						account: data.userAccount || '',
						avatar: data.userImg || ''
					})
				}
			})
		},
		// 用户名展示优先级：匿名 > 后端提供昵称/账号 > 基于userId的脱敏
		computeDisplayName(item) {
			if (!item) return '用户'
			if (item.isAnonymous) return '匿名评价'
			// 优先从 userInfoMap 读取昵称/账号
			const info = item.userId ? this.userInfoMap[item.userId] : null
			if (info && (info.nickname || info.account)) {
				return (info.nickname || info.account).trim()
			}
			// 回退：使用记录内可能存在的字段
			const raw = item.userNickname || item.nickName || item.username || item.userName || item.userAccount
			if (raw && String(raw).trim()) return String(raw).trim()
			return this.maskUserId(item.userId)
		},
		maskUserId(uid) {
			const s = String(uid || '')
			if (!s) return '用户'
			if (s.length <= 2) return `用户*${s}`
			const tail = s.slice(-2)
			return `用户***${tail}`
		},
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 显示更多选项
		showMoreOptions() {
			uni.showActionSheet({
				itemList: ['分享', '举报', '反馈'],
				success: (res) => {
					console.log('选择了第' + (res.tapIndex + 1) + '个按钮');
				}
			});
		},
		
		// 显示筛选选项
		showFilter() {
			uni.showToast({
				title: '筛选功能开发中',
				icon: 'none'
			});
		},
		
		// 显示排序选项
		showSort() {
			uni.showActionSheet({
				itemList: ['最新', '最热', '评分最高', '评分最低'],
				success: (res) => {
					this.sortReviews(res.tapIndex);
				}
			});
		},
		
		// 切换标签
		switchTab(tab) {
			this.activeTab = tab;
		},
		
		// 排序评价
		sortReviews(sortType) {
			switch(sortType) {
				case 0: // 最新
					this.reviews.sort((a, b) => new Date(b.date) - new Date(a.date));
					break;
				case 1: // 最热
					// 这里可以根据点赞数排序
					break;
				case 2: // 评分最高
					this.reviews.sort((a, b) => b.rating - a.rating);
					break;
				case 3: // 评分最低
					this.reviews.sort((a, b) => a.rating - b.rating);
					break;
			}
		},
		
		// 预览图片
		previewImage(images, current) {
			uni.previewImage({
				urls: images,
				current: current
			});
		},
		
		// 加载评价数据（从后端appraise表获取）
		async loadReviews() {
			if (!this.productId) return;
			try {
				const res = await this.fetchAppraiseList({ pageNum: 1, pageSize: 50, goodsId: this.productId });
				// 兼容 TableDataInfo 或 AjaxResult 格式
				const rows = (res && res.rows) || (res && res.data && res.data.rows) || (Array.isArray(res) ? res : []);
				// 预先拉取用户信息（排除匿名）
				await this.loadUserInfos(rows.filter(r => !r.isAnonymous).map(r => r.userId))
				const mapped = rows.map(item => {
					const imgs = (item.appraiseImg || '')
						.split(',')
						.map(s => s.trim())
						.filter(Boolean);
					const userInfo = item.userId ? this.userInfoMap[item.userId] : null
					return {
						id: item.appraiseId,
						userId: item.userId,
						isAnonymous: !!item.isAnonymous,
						username: this.computeDisplayName(item),
						avatar: (userInfo && userInfo.avatar) || '',
						rating: Number(item.appraiseScore) || 0,
						content: item.appraiseContent || '',
						date: item.appraiseTime ? this.formatDate(item.appraiseTime) : '',
						images: imgs,
						highlighted: false
					}
				});
				this.reviews = mapped;
				this.hasMore = false;
				this.loadMoreStatus = 'nomore';
				this.updateStatistics();
				this.$nextTick(() => {
					this.scrollToTargetReview()
				})
			} catch (e) {
				uni.showToast({ title: '获取评价失败', icon: 'none' });
			}
		},
			scrollToTargetReview() {
			if (!this.targetReviewId && !this.targetReviewKey) return
				const idx = this.reviews.findIndex(r => {
				if (this.targetReviewId && String(r.id) === String(this.targetReviewId)) return true
				if (this.targetReviewKey && r.content && r.content.indexOf(this.targetReviewKey) !== -1) return true
				return false
			})
			if (idx < 0) return
				// 使用节点id滚动更稳妥
				const targetId = this.reviews[idx].id ? `#review-${this.reviews[idx].id}` : `.reviews-list .review-item:nth-child(${idx + 1})`
				let nodeTop = 0
				uni.createSelectorQuery()
					.in(this)
					.select(targetId)
					.boundingClientRect(rect => { nodeTop = rect ? rect.top : 0 })
					.selectViewport()
					.scrollOffset(v => {
						const top = Math.max((v?.scrollTop || 0) + nodeTop - 80, 0)
						uni.pageScrollTo({ scrollTop: top, duration: 300 })
						// 滚动后延迟添加高亮，确保用户可见
						setTimeout(() => {
							this.$set(this.reviews[idx], 'highlighted', true)
							setTimeout(() => {
								this.$set(this.reviews[idx], 'highlighted', false)
							}, 1600)
						}, 350)
					})
					.exec()
			},

		// 格式化日期为 YYYY-MM-DD
		formatDate(input) {
			try {
				const d = new Date(input)
				const y = d.getFullYear()
				const m = `${d.getMonth() + 1}`.padStart(2, '0')
				const day = `${d.getDate()}`.padStart(2, '0')
				return `${y}-${m}-${day}`
			} catch (e) {
				return ''
			}
		},
		
		// 更新统计数据
		updateStatistics() {
			this.totalReviews = this.reviews.length;
			const positiveReviews = this.reviews.filter(review => review.rating >= 4);
			this.positiveRate = this.totalReviews > 0 ? Math.round((positiveReviews.length / this.totalReviews) * 100) : 0;
			this.positiveCount = positiveReviews.length;
			this.neutralCount = this.reviews.filter(review => review.rating === 3).length;
			this.negativeCount = this.reviews.filter(review => review.rating <= 2).length;
			this.withImageCount = this.reviews.filter(review => review.images && review.images.length > 0).length;
			this.allCount = this.totalReviews;
		},
		
		// 加载更多
		loadMore() {
			if (this.hasMore) {
				this.loadMoreStatus = 'loading';
				// 模拟加载更多数据
				setTimeout(() => {
					this.loadMoreStatus = 'nomore';
					this.hasMore = false;
				}, 1000);
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.reviews-container {
	min-height: 100vh;
	background-color: #fff;
}

.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.nav-left {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.nav-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
	}
	
	.nav-actions {
		display: flex;
		gap: 20rpx;
		
		.action-icon {
			width: 40rpx;
			height: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}

.review-summary {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.summary-left {
		.review-count {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}
	}
	
	.summary-right {
		.positive-rate {
			font-size: 28rpx;
			color: #ff4757;
			font-weight: 500;
		}
	}
}

.filter-tabs {
	display: flex;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	justify-content: space-between;
	
	.tab-item {
		flex: 1 1 0;
		text-align: center;
		padding: 12rpx 16rpx;
		margin-right: 10rpx;
		border-radius: 16rpx;
		background-color: #f8f9fa;
		border: 1rpx solid #f0f0f0;
		
		&.active {
			background-color: #ff4757;
			border-color: #ff4757;
			
			.tab-text {
				color: #fff;
			}
		}
		
		.tab-text {
			font-size: 24rpx;
			color: #666;
		}
	}
}

.instruction-text {
	padding: 20rpx 30rpx;
	background-color: #fff;
	
	.instruction {
		font-size: 24rpx;
		color: #999;
	}
}

.reviews-list {
	padding: 0 30rpx;
	
	.review-item {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;

		&.highlighted {
				/* 小程序不完全支持复杂动画，这里使用边框与阴影增强视觉反馈 */
				background-color: #fff7e6 !important;
				border-color: #ffb84d !important;
				box-shadow: 0 0 0 2rpx #ffd591 inset, 0 6rpx 18rpx rgba(255, 153, 0, 0.25);
		}
		
		&:last-child {
			border-bottom: none;
		}
		
		.review-header {
			display: flex;
			align-items: flex-start;
			justify-content: space-between;
			margin-bottom: 20rpx;
			
			.user-info {
				display: flex;
				align-items: center;
				flex: 1;
				
				.user-avatar {
					margin-right: 20rpx;
				}
				
				.user-details {
					flex: 1;
					
					.username {
						font-size: 28rpx;
						color: #333;
						margin-bottom: 8rpx;
						display: block;
					}
					
						.rating {
							display: flex;
							flex-direction: row;
							align-items: center;
							gap: 6rpx;
						}
				}
			}
			
			.review-date {
				.date-text {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
		
		.review-content {
			margin-bottom: 20rpx;
			
			.content-text {
				font-size: 28rpx;
				color: #333;
				line-height: 1.6;
			}
		}
		
		.review-images {
			display: flex;
			flex-wrap: wrap;
			gap: 10rpx;
			margin-top: 10rpx;
			
			.image-item {
				width: 32%;
				height: 0;
				padding-bottom: 32%;
				position: relative;
				overflow: hidden;
				border-radius: 8rpx;
			}

			.image-item > * {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
			}
		}
	}
}

/* 动画在部分小程序平台表现不稳定，先保留占位，主要依赖边框与阴影 */

.load-more {
	padding: 30rpx;
	text-align: center;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 30rpx;
	
	.empty-icon {
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
}
</style> 